package com.rong.shop.controller;

import com.rong.shop.pojo.Cart;
import com.rong.shop.pojo.vo.CartVO;
import com.rong.shop.service.IAddressService;
import com.rong.shop.service.ICartService;
import com.rong.shop.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/carts")
public class CartController extends BaseController{

    @Autowired
    private ICartService cartService;

    @RequestMapping({"","/"})
    @ResponseBody
    public JsonResult<List<CartVO>> findByUid(HttpSession session){
        Integer uid = getUidFromSession(session);
        List<CartVO> cars = cartService.findByUid(uid);
        return new JsonResult<List<CartVO>>(OK, cars);
    }

//  http://localhost:8080/carts/addCart?pid=10000005&amount=1
    @RequestMapping("/addCart")
    @ResponseBody
    public JsonResult<Void> addCart(HttpSession session, Integer pid, Integer amount){
        String username = getUsernameFromSession(session);
        Integer uid = getUidFromSession(session);
        cartService.addCart(uid, pid, amount, username);
        return new JsonResult<Void>(OK);
    }

//  http://localhost:8080/carts/findByCids?cids=9&cids=8&cids=7
    @RequestMapping("/findByCids")
    @ResponseBody
    public JsonResult<List<CartVO>> findByCids(HttpSession session, Integer[] cids){
        Integer uid = getUidFromSession(session);
        List<CartVO> cartVOs = cartService.findByCids(cids, uid);
        return new JsonResult<>(OK, cartVOs);
    }

    //  http://localhost:8080/carts/1/num/add
    @RequestMapping("/{cid}/num/add")
    @ResponseBody
    public JsonResult<Integer> addNumByCid(HttpSession session,@PathVariable("cid") Integer cid){
        String username = getUsernameFromSession(session);
        Integer uid = getUidFromSession(session);
        Integer num = cartService.addNum(cid, uid, username);
        return new JsonResult<Integer>(OK, num);
    }

    //  http://localhost:8080/carts/1/num/reduce
    @RequestMapping("/{cid}/num/reduce")
    @ResponseBody
    public JsonResult<Integer> reduceNumByCid(HttpSession session,@PathVariable("cid") Integer cid){
        String username = getUsernameFromSession(session);
        Integer uid = getUidFromSession(session);
        Integer num = cartService.reduceNum(cid, uid, username);
        return new JsonResult<Integer>(OK, num);
    }


}
